<template>
  <div id="postManage">
    <!--上部搜索条件组件-->
    <topSearch :form-inline="formInline" @toSearch="toSearch"></topSearch>
    <div class="table-conBtn">
      <el-button
        v-permission="'wh:system:tagCategory:add'"
        type="warning"
        icon="el-icon-plus"
        @click="addBtn"
      >
        创建标签分类
      </el-button>
      <el-button
        v-permission="'wh:system:tagCategory:remove'"
        type="warning"
        plain
        @click="delMul"
      >
        批量删除
      </el-button>
      <el-button
        v-permission="'wh:system:tagCategory:import'"
        type="warning"
        icon="el-icon-upload2"
        @click="importBtn"
      >
        批量导入
      </el-button>
      <freshCom @searchList="searchList"></freshCom>
    </div>
    <!--下部table-->
    <el-table
      v-loading="loading"
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
      max-height="490"
      ref="table"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column type="index" width="60" label="序号">
        <template slot-scope="scope">
          {{
            scope.$index
              | filterPage(searchParams.pageNum, searchParams.pageSize)
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="标签分类ID"
        prop="id"
        show-overflow-tooltip
        min-width="120"
      ></el-table-column>
      <el-table-column
        label="标签分类名称"
        prop="tagCategoryName"
        min-width="130"
      ></el-table-column>
      <el-table-column
        label="拥有标签数"
        prop="tagCount"
        min-width="130"
      ></el-table-column>
      <el-table-column label="状态" prop="platformName" min-width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            :active-value="true"
            :inactive-value="false"
            active-color="#1DC8A4"
            @change="
              changeStatus(scope.row.enabled, scope.row.id, scope.$index)
            "
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="创建者"
        prop="createdBy"
        min-width="120"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        show-overflow-tooltip
        prop="createdDate"
        width="150"
      >
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="130">
        <template slot-scope="scope">
          <el-button
            v-permission="'wh:system:tagCategory:remove'"
            type="text"
            @click="
              delSingle(
                scope.row.id,
                scope.row.tagCategoryName,
                scope.row.enabled
              )
            "
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-全局组件-->
    <pageCom
      :searchParams="searchParams"
      :total="total"
      @searchList="searchList"
    ></pageCom>
    <dialogAddEdit
      v-if="dialogData.isShow"
      :dialog-data="dialogData"
      @refresh="refresh"
    ></dialogAddEdit>
    <!-- 导入弹窗 -->
    <importDialog
      v-if="importDialogData.isShow"
      :dialog-data="importDialogData"
      @refresh="refresh"
      @showError="showError"
    ></importDialog>
    <!-- 导入失败弹窗 -->
    <errorDialog
      v-if="errorDialogData.isShow"
      :dialog-data="errorDialogData"
      :from="showDownLoad ? 'tagCategory' : ''"
    ></errorDialog>
  </div>
</template>

<script>
import {
  getCategoriesList,
  getUserCount,
  multipleDel,
  singleDel,
  changeStatus,
  importUrl,
  downUrl
} from '@/api/lableManage/tagCategory' // 接口
import topSearch from '@component/lableManage/tagCategory/topSearch' // 上部搜索条件
import dialogAddEdit from '@component/lableManage/tagCategory/dialogAddEdit' // 新增/编辑弹窗
import importDialog from '@common/importDialog' // 导入弹窗
import errorDialog from '@common/errorDialog' // 导入失败弹窗
import { saveScrollMixins } from '@/mixins/saveScroll'
export default {
  name: 'tagsClassifyManage',
  msg: '标签分类管理',
  mixins: [saveScrollMixins],
  components: {
    topSearch,
    dialogAddEdit,
    importDialog,
    errorDialog
  },
  data() {
    return {
      loading: false,
      total: 0,
      tableData: [], // table内容
      searchParams: {
        pageNum: 1, // 当前页数
        pageSize: 10, // 页面显示条数
        sort: 'createdDate,desc' // 排序字段
      },
      formInline: {
        // 搜索条件
        tagSelectType: '', // 搜索方式
        status: '', // 状态（启用:true/停用:false）默认为启用
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        id: '', // 标签分类ID
        tagCategoryName: '', // 标签分类名称
        createTime: []
      },
      dialogData: {
        isShow: false, // 默认隐藏
        type: 'add', // 默认新增
        postId: null // 编辑时，传递的参数
      },
      // 传递给导入弹框的数据
      importDialogData: {
        title: '创建标签分类',
        url: '', // 导入接口
        downUrl: '', // 下载模板接口
        isShow: false, // 控制弹框显示
        params: '' // 参数
      },
      // 导入失败弹框的数据
      errorDialogData: {
        isShow: false, // 控制弹框显示
        warningText: '' // 参数
      },
      multipleSelection: [],
      showDownLoad: false //是否显示“下载失败数据”按钮
    }
  },
  activated() {
    this.toTableScrollHeight()
  },
  mounted() {
    this.searchList()
    this.$nextTick(() => {
      setTimeout(() => {
        this.setTableScrollHeight()
      }, 1000)
    })
  },
  methods: {
    /* 获取列表 */
    searchList() {
      this.loading = true
      let obj = Object.assign({}, this.searchParams, this.formInline)
      obj[this.formInline.options] = this.formInline.text
      delete obj.options
      delete obj.text
      getCategoriesList(
        obj,
        (response) => {
          this.loading = false
          this.tableData = response.rows
          this.total = response.total
        },
        (response) => {
          this.loading = false
          this.$message.warning(response.message)
        }
      )
    },
    /* table选择 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /* 换页 */
    changePage(page) {
      this.searchParams.pageNum = page
      this.searchList()
    },
    /* 新增 */
    addBtn() {
      this.dialogData.isShow = true
    },
    // 导入
    importBtn() {
      this.importDialogData.url = importUrl() // 导入接口
      this.importDialogData.downUrl = downUrl() // 下载模板接口
      this.importDialogData.isShow = true // 显示导入弹框
    },
    /* 批量删除 */
    delMul() {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请至少选择一条数据！')
        return
      }
      this.$confirm(
        `删除标签分类后，标签分类下的用户将无此标签分类，确定要删除该标签分类?`,
        '删除提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        let item = this.multipleSelection.find((item) => item.enabled)
        if (item) {
          this.$alert(
            `标签分类名称:[${item.tagCategoryName}],已启用，不能删除`,
            '系统提示',
            {
              confirmButtonText: '确定',
              type: 'warning'
            }
          )
        } else {
          let ids = []
          this.multipleSelection.forEach((item) => {
            ids.push(item.id)
          })
          let obj = {
            ids: ids.join(',')
          }
          multipleDel(
            obj,
            (response) => {
              this.searchList()
            },
            (response) => {
              this.$message.warning('删除失败,' + response.message)
            }
          )
        }
      })
    },
    /* 删除单个 */
    async delSingle(id, name, status) {
      let n = await this.getCount(id)
      if (n === 'Null') {
        return
      }
      this.$confirm(
        `此标签分类下有：${n}个用户， 删除分类后，标签分类下的用户将无此标签，确定要删除该分类？`,
        '删除提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        if (status === true) {
          this.$alert(`标签分类名称:[${name}],已启用，不能删除`, '系统提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        } else {
          singleDel(
            id,
            (response) => {
              this.searchList()
            },
            (response) => {
              this.$message.warning('删除失败,' + response.message)
            }
          )
        }
      })
    },
    /*获取标签分类下的用户数量*/
    getCount(id) {
      let _this = this
      return new Promise((resolve, reject) => {
        getUserCount(
          id,
          (response) => {
            resolve(response)
          },
          (response) => {
            _this.$message.warning(response.message)
            resolve('Null')
          }
        )
      })
    },
    // 状态切换提示
    async changeStatus(status, id, index) {
      let _this = this
      if (status === false) {
        let n = await this.getCount(id)
        if (n === 'Null') {
          this.tableData[index].enabled = true
          return
        }
        // 关闭
        this.$confirm(
          `此标签分类下有：${n}个用户， 停用分类后，标签分类下的用户将无此标签，确定要停用该分类？`,
          '系统提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
          .then(() => {
            _this.changeStatusRequire(status, id, index)
          })
          .catch(() => {
            this.tableData[index].enabled = true

            // this.$message({
            //   type: 'info',
            //   message: '已取消停用'
            // })
          })
      } else {
        // 启用
        this.$confirm('确认要启用该分类吗？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            _this.changeStatusRequire(status, id, index)
          })
          .catch(() => {
            this.tableData[index].enabled = false
            /* this.$message({
                 type: "info",
                 message: "已取消启用"
               }); */
          })
      }
    },
    /* 改变状态，请求接口 */
    changeStatusRequire(status, id, index) {
      let url = `/tag-categories/${id}/`
      let str = status ? 'enable' : 'disable'
      url += str
      changeStatus(
        id,
        status,
        (response) => {
          let mes = status === false ? '已停用' : '已启用'
          this.$message.success(response)
        },
        (response) => {
          this.tableData[index].enabled = true
          this.$message.warning(response.message)
        }
      )
    },
    /* 导入失败弹窗 */
    showError(text, res) {
      this.errorDialogData.isShow = true // 显示导入失败弹框
      this.errorDialogData.warningText = text // 显示导入失败弹框
      this.showDownLoad = res.identification
    },
    /* 新增编辑后，刷新列表 */
    refresh() {
      this.toSearch()
    },
    /* 搜索 */
    toSearch() {
      this.searchParams.pageNum = 1
      this.searchList()
    }
  }
}
</script>

<style lang="less">
// #postManage {
//   .table-conBtn {
//   }
// }
</style>
